<?php
namespace My\Controller;

use Utuo\BackgroundController;

class DriverTermController extends BackgroundController {
	
	private $status = array(
		'0' => '禁用',
		'1' => '启用',
	);
	
	public function _initialize() {
		$this->setControllerTitle("活动期次管理");
		$this->setActionTitle(array(
				'index' => '投票活动列表',
				'add' => '添加投票活动',
				'modify' => '投票活动修改',
				'config' => '配置投票',
				'recycle' => '回收站',
		));
		$this->setActionNav("index,add,recycle");
	}
	
	public function getLists($is_deleted = 0) {
		$status = I("status", -1, 'intval');
		$page = I('p', 0, 'intval');
		$condition = array(
				'a.is_deleted' => $is_deleted,
				'a.cid' => $this->aid,
		);
		$m = M("DriverTerm a")->where( $condition )->field("a.*");
		$n = clone $m;
		$termCount = $n->count();
		$termLists = $m->page($page)->limit($this->pageSize)->order("a.id desc")->select();
		$this->showPage($termCount, $this->pageSize);
		$this->assign("termLists", $termLists);
		$this->display();
	}
	
	public function rankAction(){
	    $termId = I('id',0,'intval');
	    $driverLists = M('Driver')->where(array('term_id'=>$termId))->order('vote DESC')->limit(300)->select();
	    
	    $driverTerm = M('DriverTerm')->where('cid=%d', $this->aid)->find($termId);
	    $termConfig = unserialize($driverTerm['config']);
	    
	    $rank = new \Utuo\Rank(array(
	        'namespace' => $termConfig['rank_name']
	    ));
	    
	    foreach ($driverLists as &$driver){
	        $driver['rank'] = $rank->getRank($driver['id']) === false ? '-' : $rank->getRank($driver['id']) + 1;
	        $driver['cleanVote'] = M('DriverVote')->where(array('term_id'=>$driver['term_id'],'driver_id'=>$driver['id']))->getField('count(distinct ip) as vCount');
	    }
	    
	    $this->assign('driverLists',$driverLists);
	    $this->display();
	}
	
	// 添加
	public function addAction() {
		$driverTerm['statusRadio'] = $this->getRadio( "status", $this->status, 0 );
		$this->assign("driverTerm", $driverTerm);
		$this->display('save');
	}
	
	// 修改
	public function modifyAction() {
		$model = CONTROLLER_NAME;
		$config = D($model)->getOneById();
		$config['statusRadio'] = $this->getRadio( "status", $this->status, $config['status'] );
		$this->assign("driverTerm", $config);
		$this->display("save");
	}
	
	// 保存
	public function saveAction() {
		$this->submitPost("DriverTerm");
	}
	
	// 配置
	public function configAction() {
		$model = CONTROLLER_NAME;
		$driverTerm = D($model)->getOneById();
		$driverTerm['config'] = unserialize( $driverTerm['config'] );
		$this->assign("driverTerm", $driverTerm);
		$this->display();
	}
	
	// 提交配置
	public function configPostAction() {
		$d = D("DriverTerm");
		$d->setupConfigValid();
		$this->submitPost("DriverTerm");
	}
	
}
